import {createRouter, createWebHistory} from 'vue-router'
import {useRouteStore, useUserStore} from '@/stores/index.js'
import {constantRoutes} from "@/routers/routes.js";


const router = createRouter({
    routes: [...constantRoutes],
    history: createWebHistory()
})


router.beforeEach(async (to, from, next) => {
    const userStore = useUserStore()
    const routeStore = useRouteStore()
    if (!userStore.userInfo) {
        // 1. 尝试获取用户信息
        await userStore.getUserInfo()
        if (!userStore.userInfo) {
            if (to.path === "/login") {
                next()
            } else {
                next({path: '/login', query: {redirect: to.path}})
            }
        } else {
            // 2. 获取动态路由信息
            await routeStore.getRoutes(userStore.userInfo.uid)
            next({...to, replace: true})
        }
    } else {
        // 已经登录，访问/login,会重定向到 / (首页)
        if (to.path === '/login') {
            next('/home')
        } else {
            next()
        }
    }
})

export default router
